package com.cz.nongyetongv5.utils;

import android.content.Context;
import android.graphics.drawable.Drawable;
import android.text.Spannable;
import android.text.SpannableString;
import android.text.style.ImageSpan;
import android.util.Log;
import android.util.Xml;

import com.cz.nongyetongv5.R;

import org.xmlpull.v1.XmlPullParser;
import org.xmlpull.v1.XmlPullParserException;

import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class EmojiUtil {
	private static final String TAG = EmojiUtil.class.getName();

	private static final String REGEX_STR = "\\[e\\](.*?)\\[/e\\]";

	// 用来保存emoji表情的转换��a表
	private Map<List<Integer>, String> convertMap = new HashMap<List<Integer>, String>();

	private Context context = null;

	public EmojiUtil(Context context) {

		this.context = context;

		// 获得emoji的xml进行

		// 创建XML转换器
		XmlPullParser pullParser = Xml.newPullParser();

		// 下面读取XML

		try {
			InputStream stream = context.getAssets().open("emoji/emoji.xml");

			pullParser.setInput(stream, "UTF-8");

			int eventCode = pullParser.getEventType();

			while (eventCode != XmlPullParser.END_DOCUMENT) {

				switch (eventCode) {

					// 如果独到的是开始标签
					case XmlPullParser.START_TAG:
						if (pullParser.getName().equals("e")) {

							String emoji = pullParser.nextText();

							List<Integer> emojiCodepoint = new ArrayList<Integer>();

							if (emoji.lastIndexOf('_') > -1) {

								String[] froms = emoji.split("\\_");

								for (String emojiUnicodeUnit : froms) {

									emojiCodepoint.add(Integer.parseInt(
											emojiUnicodeUnit, 16));
								}
							} else {
								emojiCodepoint.add(Integer.parseInt(emoji, 16));
							}

							convertMap.put(emojiCodepoint, emoji);
						}
						break;

				}

				eventCode = pullParser.next();
			}

			Log.d(TAG, "转换XML成功,当前解析的emoji总数为:" + convertMap.size());
		} catch (NumberFormatException e) {
			Log.d(TAG, "emoji unicode 转换 16进制 符号 出现错误:" + e.getMessage());
		} catch (FileNotFoundException e) {
			Log.d(TAG, "emoji unicode xml 没有找到 出现错误:" + e.getMessage());
		} catch (XmlPullParserException e) {
			Log.d(TAG, "emoji unicode xml 解析 出现错误:" + e.getMessage());
		} catch (IOException e) {
			Log.d(TAG, "emoji unicode xml io 出现错误:" + e.getMessage());
		} catch (Exception e) {
			Log.d(TAG, "emoji unicode xml  出现错误:" + e.getMessage());
		}
	}

	/**
	 * 将输入的字符串转换为包含表情的字符串
	 */

	public String parseEmoji(String input) {

		if (input == null || input.length() <= 0) {
			return "";
		}

		StringBuilder result = new StringBuilder();

		int[] codePoints = toCodePointArray(input);

		List<Integer> key = null;

		for (int i = 0; i < codePoints.length; i++) {

			key = new ArrayList<Integer>();

			if (i + 1 < codePoints.length) {

				key.add(codePoints[i]);

				key.add(codePoints[i + 1]);

				// 检测有没有匹配两个unicode字符的
				if (convertMap.containsKey(key)) {
					String value = convertMap.get(key);
					if (value != null) {
						result.append("[e]" + value + "[/e]");
					}

					i++;
					continue;
				}
			}
			key.clear();
			key.add(codePoints[i]);
			// 检测匹配1个unicode的表情
			if (convertMap.containsKey(key)) {
				String value = convertMap.get(key);
				if (value != null) {
					result.append("[e]" + value + "[/e]");
				}
				continue;
			}
			// 如果没有匹配到则增加字符,因为不是表情
			result.append(Character.toChars(codePoints[i]));
		}
		return result.toString();
	}

	// 将字符串转换为代码点数组

	private int[] toCodePointArray(String str) {

		char[] ach = str.toCharArray();

		int len = ach.length;

		int[] acp = new int[Character.codePointCount(ach, 0, len)];

		int j = 0;

		for (int i = 0, cp; i < len; i += Character.charCount(cp)) {

			cp = Character.codePointAt(ach, i);

			acp[j++] = cp;
		}

		return acp;
	}

	/**
	 * @desc <pre>
	 * 解析字符串中的表情字符串替换成表情图片
	 * </pre>
	 * @author Weiliang Hu
	 * @date 2013-12-17
	 * @param context
	 * @param str
	 * @return
	 */
	public SpannableString getExpressionString(Context context, String str) {
		SpannableString spannableString = new SpannableString(str);

		Pattern patten = Pattern.compile(REGEX_STR, Pattern.CASE_INSENSITIVE);

		try {
			Matcher matcher = patten.matcher(spannableString);

			while (matcher.find()) {
				String key = matcher.group();

				Field field = R.drawable.class.getDeclaredField("empji_"
						+ matcher.group(1));

				int resId = Integer.parseInt(field.get(null).toString());

				if (resId != 0) {

					Drawable drawable = context.getResources().getDrawable(
							resId);
					drawable.setBounds(0, 0, drawable.getIntrinsicWidth(),
							drawable.getIntrinsicHeight());

					ImageSpan imageSpan = new ImageSpan(drawable);

					int end = matcher.start() + key.length();

					spannableString.setSpan(imageSpan, matcher.start(), end,
							Spannable.SPAN_INCLUSIVE_EXCLUSIVE);

				}
			}
		} catch (Exception e) {
			Log.d(TAG, e.getMessage());
		}

		return spannableString;
	}
}
